package com.org.devg.monitor.server.components.task;

import org.devgframwork.es5.elasticserach.EsSearch;
import com.org.devg.monitor.server.model.MonitorServerConfig;
import org.devgframwork.platform.utils.LocalDateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.concurrent.TimeUnit;

@Component
public class EsMonitorIndexClear {

    private static final Logger logger = LoggerFactory.getLogger(EsMonitorIndexClear.class);

    private static final String lockName = "devg-monitor:esclear";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MonitorServerConfig monitorServerConfig;

    @Scheduled(cron = "0 0/30 * * * ?")
    public void executeFileDownLoadTask() {
        boolean bool = stringRedisTemplate.opsForValue().setIfAbsent(lockName, "1", 5, TimeUnit.MINUTES);
        if (!bool) {
            logger.error("清理ES数据运行中");
            return;
        }
        int from = (monitorServerConfig.getClearEsIndexFrom() == null ? 7 : monitorServerConfig.getClearEsIndexFrom());
        int size = (monitorServerConfig.getClearEsIndexSize() == null ? 5 : monitorServerConfig.getClearEsIndexSize());
        for (int i = from; i < (from + size); i++) {
            String esIndexDay = LocalDateUtil.localDateFormat(LocalDate.now().minusDays(i), LocalDateUtil.FORMAT_PATTERN4);
            String esIndexName = "monitor_message_consumer_" + esIndexDay;
            boolean existsEsName = EsSearch.indicesExists(esIndexName);
            logger.info("esIndexName:{},exists:{}", esIndexName, existsEsName);
            if (existsEsName) {
                boolean deleteIndexBool = EsSearch.deleteIndex(esIndexName);
                logger.info("delete esIndexName:{} success:{}", esIndexName, deleteIndexBool);
            }
        }
        stringRedisTemplate.delete(lockName);
    }
}
